package cn.ultrarisk.scadmin.manager.util;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * web开发工具类
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2013-11-4
 * @since V1.0
 */
public class WebUtil {
    /**
     * 获取客户端IP地址
     *
     * @query request
     * @return
     */
    public static String getRemoteIP(HttpServletRequest request) {
        String forwardIP = StringUtil.isNotEmpty(request.getHeader("X-FORWARDED-FOR")) ? request.getHeader("X-FORWARDED-FOR") : request.getRemoteAddr();
        if ((StringUtil.isNotEmpty(forwardIP)) && forwardIP.contains(",")) {
            return forwardIP.split(",")[0];
        }
        return forwardIP;
    }

    private static String encodeParamValue(String s) {
        try {
            return URLEncoder.encode(s, "utf-8");
        } catch (UnsupportedEncodingException ignored) {
        }
        return s;
    }

    public static String getParamStr(Map<String, Object> querys) {
        List<String> queryList = new ArrayList<String>();
        if (querys != null) {
            for (String key : querys.keySet()) {
                String value = querys.get(key) != null ? String.valueOf(querys.get(key)) : null;
                if (StringUtil.isNotEmpty(value)) {
                    queryList.add(key + "=" + encodeParamValue(value));
                }
            }
        }
        return CollectionUtil.join(queryList, "&");
    }

    public static String get(String url, Map<String, Object> querys) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            String urlWithParam = url + (url.contains("?") ? "&" : "?") + getParamStr(querys);
            HttpGet httpGet = new HttpGet(urlWithParam);

            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                return IOUtil.in2Str(response.getEntity().getContent(), "UTF-8");
            }
            throw new IOException(String.format("http get request[%s] failure", urlWithParam));
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
    }

    public static String post(String url, Map<String, Object> querys, String data, String contentType) throws IOException {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            String urlWithParam = url + (url.contains("?") ? "&" : "?") + getParamStr(querys);
            HttpPost httpPost = new HttpPost(urlWithParam);
            httpPost.setHeader("Content-Type", contentType);
            ByteArrayEntity entity = new ByteArrayEntity(data.getBytes());
            httpPost.setEntity(entity);

            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                return IOUtil.in2Str(response.getEntity().getContent(), "UTF-8");
            }
            throw new IOException(String.format("http post request[%s] failure", urlWithParam));
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
            if (response != null) {
                response.close();
            }
        }
    }
}
